package com.becca.cake.service.companyEatApply.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.becca.cake.core.code.SeriNumber;
import com.becca.cake.core.excel.excelWriter.ExcelInfo;
import com.becca.cake.core.excel.excelWriter.impl.ExcelWriteHandle;
import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.core.sms.SMSHelper;
import com.becca.cake.core.sms.message.SmsCompanyApplyNoPass;
import com.becca.cake.core.sms.message.SmsCompanyApplyPass;
import com.becca.cake.dao.companyEatApply.CompanyEatApplyDAO;
import com.becca.cake.dao.fixing.FixingDAO;
import com.becca.cake.dao.goods.GoodsDAO;
import com.becca.cake.dao.order.OrderDAO;
import com.becca.cake.dao.system.DataDictionaryDAO;
import com.becca.cake.dao.users.UserManagerDAO;
import com.becca.cake.model.activity.CompanyEatApplyModel;
import com.becca.cake.model.goods.GoodsFixingModel;
import com.becca.cake.model.goods.GoodsModel;
import com.becca.cake.model.goods.GoodsPriceSizeModel;
import com.becca.cake.model.order.OrderDetailsModel;
import com.becca.cake.model.order.OrderModel;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.model.users.UserPaymentsModel;
import com.becca.cake.model.users.UsersModel;
import com.becca.cake.service.companyEatApply.ICompanyEatApplyService;
import com.becca.cake.util.DateUtils;
import com.becca.cake.util.StringUtil;

/**
 * 试吃申请审核与下单Service实现类
 * @copyright  尊星(上海)信息科技有限公司
 * @author yellow
 * @date 2016年7月20日 下午4:48:26
 */
@Service
public class CompanyEatApplyServiceImpl implements ICompanyEatApplyService {
    private static final Logger logger = LoggerFactory.getLogger(CompanyEatApplyServiceImpl.class);
    @Autowired
    private CompanyEatApplyDAO  companyEatApplyDAO;

    @Autowired
    private DataDictionaryDAO   dataDictionaryDAO;

    @Autowired
    private OrderDAO            orderDAO;

    @Autowired
    private GoodsDAO            goodsDAO;

    @Autowired
    private UserManagerDAO      userManagerDAO;

    @Autowired
    private FixingDAO           fixingDAO;

    @Override
    public List<CompanyEatApplyModel> selectCompanyEatApply(Map<String, Object> map)
                                                                                    throws Exception {
        return this.companyEatApplyDAO.selectCompanyEatApply(map);
    }

    @Override
    public Long selectCompanyEatApplyCount(Map<String, Object> map) throws Exception {
        return this.companyEatApplyDAO.selectCompanyEatApplyCount(map);
    }

    @Override
    public CompanyEatApplyModel selectCompanyEatApplyById(Integer id) throws Exception {
        return this.companyEatApplyDAO.selectCompanyEatApplyById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void updCompanyEatApplyById(CompanyEatApplyModel companyEatApplyModel) throws Exception {
        // 1.step 校验数据
        CompanyEatApplyModel.validateSaveCompanyEatApply(companyEatApplyModel);
        // 2.step 编辑数据
        this.companyEatApplyDAO.updCompanyEatApplyById(companyEatApplyModel);
    }

    //试吃 不通过
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void companyApplyEatdNoPass(Integer id, String noPassReason) throws Exception {
        //step1:校验数据
        CompanyEatApplyModel.validateUpdateApplyStatus(id);

        // 判断是否已未通过处理
        Map<String, Object> notPassMap = new HashMap<String, Object>();
        notPassMap.put("id", id);
        notPassMap.put("applyStatus", CompanyEatApplyModel.APPLY_STATUS_NO_PASS);
        Long isExistPassedOrNot = this.companyEatApplyDAO.isExistPassedOrNot(notPassMap);
        if (isExistPassedOrNot != 0) {
            throw new ServiceException(CompanyEatApplyModel.APPLY_NOT_PASSED);
        }

        //step2:根据id查询该试吃申请对象
        CompanyEatApplyModel companyEatApplyModel = this.companyEatApplyDAO
            .selectCompanyEatApplyById(id);
        if (companyEatApplyModel == null) {
            throw new ServiceException(CompanyEatApplyModel.COMPANY_MODEL_NULL);
        }
        //step3:发送短信
        String applyUserPhone = companyEatApplyModel.getApplyUserPhone();
        if (StringUtil.isMobileTel(applyUserPhone)) {
            SmsCompanyApplyNoPass applyNoPass = new SmsCompanyApplyNoPass(applyUserPhone,
                noPassReason);
            if (SMSHelper.sendMessage(applyNoPass)) {
                logger.info("申请试吃信息已被拒绝!");
            }
        }
        //step4:修改申请状态
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("applyStatus", CompanyEatApplyModel.APPLY_STATUS_NO_PASS);
        map.put("noPassReason", noPassReason);
        this.companyEatApplyDAO.updNoPassApplyById(map);
    }
    
    

    @Override
    public List<CompanyEatApplyModel> selectCompanyEatApplyToExcel(String ids)
                                                                              throws ServiceException {
        if (StringUtil.isNotEmpty(ids)) {
            return this.companyEatApplyDAO.selectCompanyEatApplyToExcel(ids);
        } else {
            throw new ServiceException(CompanyEatApplyModel.IDS_NULL);
        }
    }

    @Override
    public void exportCompanyEatApplyToExcel(HttpServletRequest request,
                                             HttpServletResponse response, List list)
                                                                                     throws ServiceException {
        ExcelInfo info = new ExcelInfo();
        info.setColumnHeader("企业试吃编号,公司名称,公司地址,试吃人数 ,申请部门,申请人,申请人手机号,公司电话");
        info.setFeilds("id,companyName,companyAddress,employeeNum,applyDepartment,applyUserName,applyUserPhone,companyTel");
        info.setDatas(list);
        info.setSheetName("企业试吃申请信息");
        info.setFileName(DateUtils.getStringToday() + "企业试吃申请信息");
        ExcelWriteHandle.getInstance().writeEcxcel(info, request, response);
    }
    
    //企业试吃审核 通过

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void companyEatApplyReviewPass(Integer id, String trueName) {
        //step1:校验数据
        CompanyEatApplyModel.validateUpdateApplyStatus(id);

        // 判断是否已通过处理
        Map<String, Object> passMap = new HashMap<String, Object>();
        passMap.put("id", id);
        passMap.put("applyStatus", CompanyEatApplyModel.APPLY_STATUS_APPLYING);
        Long isExistPassedOrNot = this.companyEatApplyDAO.isExistPassedOrNot(passMap);
        if (isExistPassedOrNot == 0) {
            throw new ServiceException(CompanyEatApplyModel.APPLY_PASSED);
        }

        //step2:根据id查询该试吃申请对象
        CompanyEatApplyModel companyEatApplyModel = this.companyEatApplyDAO
            .selectCompanyEatApplyById(id);
        if (companyEatApplyModel == null) {
            throw new ServiceException(CompanyEatApplyModel.COMPANY_MODEL_NULL);
        }

        //step4:修改申请状态
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("updatedName", trueName);
        map.put("applyStatus", CompanyEatApplyModel.APPLY_STATUS_PASS);
        this.companyEatApplyDAO.companyEatApplyReviewPass(map);

        //step5:发送短信
        String applyUserPhone = companyEatApplyModel.getApplyUserPhone();
        if (StringUtil.isMobileTel(applyUserPhone)) {
            SmsCompanyApplyPass applyPass = new SmsCompanyApplyPass(applyUserPhone);
            if (SMSHelper.sendMessage(applyPass)) {
                logger.info("申请试吃信息已通过!");
            }
        }

    }
   //企业试吃下单操作

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void companyEatApplyOrderPass(Integer id, Integer goodsPriceSizeId, String deliveryDate,
                                         String deliveryTimes, String trueName) {

        //step1:校验数据
        CompanyEatApplyModel.validateCompanyEatApplyPassParam(id, goodsPriceSizeId, deliveryDate,
            deliveryTimes);

        // 判断是否已进行下单处理
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", id);
        map.put("applyStatus", CompanyEatApplyModel.APPLY_STATUS_PASS);

        Long isExistPassedOrNot = this.companyEatApplyDAO.isExistPassedOrNot(map);
        if (isExistPassedOrNot == 0) {
            throw new ServiceException(CompanyEatApplyModel.APPLY_ORDER);
        }

        //step2:查询该试吃下单信息
        CompanyEatApplyModel companyEatApplyModel = this.companyEatApplyDAO
            .selectCompanyEatApplyById(id);
        if (companyEatApplyModel == null) {
            throw new ServiceException(CompanyEatApplyModel.COMPANY_MODEL_NULL);
        }

        //step3:查询选择的商品规格信息
        GoodsPriceSizeModel goodsPriceSizeModel = this.goodsDAO
            .selectGoodsPriceSizeModelById(goodsPriceSizeId);
        if (goodsPriceSizeModel == null) {
            throw new ServiceException(GoodsPriceSizeModel.GOODS_PRICE_NO_EXISTS);
        }

        //step4：查询对应商品信息
        GoodsModel goodsModel = this.goodsDAO.selectGoodsById(goodsPriceSizeModel.getGoodsId());
        if (goodsModel == null) {
            throw new ServiceException(GoodsModel.GOODS_NULL);
        }

        //step5:查询试吃用户信息
        Map<String, Object> userMap = new HashMap<String, Object>();
        userMap.put("userType", UsersModel.USER_TYPE_APPLY_EAT);
        userMap.put("status", UsersModel.USER_STATUS_USABLE);
        Integer userId = this.userManagerDAO.selectUserOfInsertOrder(userMap);
        if (userId == null) {
            throw new ServiceException(UsersModel.USER_ID_NULL);
        }

        //step6:查询配件集合
        Map<String, Object> fixingMap = new HashMap<String, Object>();
        fixingMap.put("isEnable", GoodsFixingModel.IS_ENABLE);
        fixingMap.put("fixingType", GoodsFixingModel.FIXING_TYPE_GIVE);
        List<GoodsFixingModel> fixingList = this.fixingDAO.selectFixingsByFixingType(fixingMap);

        //step7:获取配送日期

        //step8:添加订单信息
        OrderModel orderModel = new OrderModel();
        orderModel.setUserId(userId);
        orderModel.setOrderStatus(OrderModel.ORDER_STATUS_CONFIRM);
        orderModel.setOrderType(OrderModel.ORDER_TYPE_APPLYEAT);
        orderModel.setPayStatus(OrderModel.ORDER_STATUS_PAY);
        orderModel.setPayType(OrderModel.PAY_TYPE_NULL);
        orderModel.setTotalAmount(goodsPriceSizeModel.getGoodsPrice());
        orderModel.setGoodsNumber(GoodsModel.GOODS_NUMBER_ONE);
        orderModel.setPayAmount(OrderModel.PAY_NOTHING_MONEY);
        orderModel.setIsNeedInvoice(OrderModel.NEED_INVOICE_NO);
        orderModel.setIsReferenceInvoice(OrderModel.NEED_INVOICE_NO);
        orderModel.setDeliveryFee(OrderModel.PAY_NOTHING_MONEY);
        orderModel.setCouponType(OrderModel.COUPON_TYPE_NO);

        orderModel.setDeliveryDate(DateUtils.toShortDateTime(deliveryDate));
        orderModel.setDeliveryTimes(deliveryTimes);
        orderModel.setConsignAddress(companyEatApplyModel.getCompanyAddress());
        orderModel.setConsignPhone(companyEatApplyModel.getApplyUserPhone());
        orderModel.setConsignee(companyEatApplyModel.getApplyUserName());
        orderModel.setCreatedName(trueName);
        orderModel.setPayGoodsName(goodsModel.getGoodsName());
        this.orderDAO.insertOrder(orderModel);

        //添加订单流水
        UserPaymentsModel paymentsModel = new UserPaymentsModel();
        paymentsModel.setUserId(orderModel.getUserId());
        paymentsModel.setOrderId(orderModel.getId());
        paymentsModel.setTotalAmount(orderModel.getPayAmount());
        paymentsModel.setStatus(UserPaymentsModel.PAYMENT_STATUS_SUCCESS);
        paymentsModel.setPayWays(orderModel.getPayType());
        paymentsModel.setPayNo("10000");
        this.orderDAO.addUserPayments(paymentsModel);
        //step8:获取订单订单编号
        Integer orderId = orderModel.getId();
        //step9:生成订单编码
        String orderCode = SeriNumber.getOrderCode(orderId);
        Map<String, Object> orderCodeMap = new HashMap<String, Object>();
        orderCodeMap.put("orderId", orderId);
        orderCodeMap.put("orderCode", orderCode);
        orderCodeMap.put("userPaymentId", paymentsModel.getId());
        this.orderDAO.updateOrderCode(orderCodeMap);

        //step10:添加订单详情
        List<OrderDetailsModel> orderDetailList = new ArrayList<OrderDetailsModel>();
        //添加商品
        OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
        Double subTotal = goodsPriceSizeModel.getGoodsPrice() * GoodsModel.GOODS_NUMBER_ONE;
        orderDetailsModel.setOrderId(orderId);
        orderDetailsModel.setGoodId(goodsModel.getId());
        orderDetailsModel.setGoodsCode(goodsModel.getGoodsCode());
        orderDetailsModel.setGoodsStandardCode(goodsPriceSizeModel.getGoodsStandardCode());
        orderDetailsModel.setGoodsName(goodsModel.getGoodsName());
        orderDetailsModel.setGoodsSize(goodsPriceSizeModel.getGoodsSize());
        orderDetailsModel.setGoodsWeight(goodsPriceSizeModel.getGoodsWeight());
        orderDetailsModel.setGoodsUnits(goodsPriceSizeModel.getGoodsUnits());
        orderDetailsModel.setGoodsPrice(goodsPriceSizeModel.getGoodsPrice());
        orderDetailsModel.setGoodsType(GoodsModel.GOODS_TYPE_DEFALUT);
        orderDetailsModel.setGoodsNumber(GoodsModel.GOODS_NUMBER_ONE);
        orderDetailsModel.setSubTotal(subTotal);
        orderDetailsModel.setCreatedName(trueName);
        orderDetailList.add(orderDetailsModel);
        //添加配件信息
        OrderDetailsModel orderFixDetailsModel = null;
        for (GoodsFixingModel goodsFixingModel : fixingList) {
            orderFixDetailsModel = new OrderDetailsModel();
            //配件总数
            int giveGoodsfixingNum = goodsPriceSizeModel.getGiveLaidNumber()
                                     * goodsFixingModel.getFixingMultiple()
                                     * orderModel.getGoodsNumber();
            orderFixDetailsModel.setOrderId(orderId);
            orderFixDetailsModel.setGoodId(goodsFixingModel.getId());
            orderFixDetailsModel.setGoodsCode(goodsFixingModel.getFixingCode());
            orderFixDetailsModel.setGoodsName(goodsFixingModel.getFixingName());
            orderFixDetailsModel.setGoodsUnits(goodsFixingModel.getFixingUnits());
            orderFixDetailsModel.setGoodsPrice(goodsFixingModel.getFixingPrice());
            orderFixDetailsModel.setGoodsType(GoodsModel.GOODS_TYPE_PARTS);
            orderFixDetailsModel.setGoodsNumber(giveGoodsfixingNum);
            //配件总价
            orderFixDetailsModel
                .setSubTotal(giveGoodsfixingNum * goodsFixingModel.getFixingPrice());
            orderFixDetailsModel.setCreatedName(trueName);
            orderDetailList.add(orderFixDetailsModel);
        }
        Map<String, Object> orderDetailMap = new HashMap<String, Object>();
        orderDetailMap.put("orderDetailList", orderDetailList);
        this.orderDAO.insertOrderDetails(orderDetailMap);

        //step11:修改试吃申请信息
        Map<String, Object> companyEatApplyMap = new HashMap<String, Object>();
        companyEatApplyMap.put("id", id);
        companyEatApplyMap.put("orderId", orderId);
        companyEatApplyMap.put("goodsPriceSizeId", goodsPriceSizeModel.getId());
        companyEatApplyMap.put("applyStatus", CompanyEatApplyModel.APPLY_STATUS_ORDER);
        companyEatApplyMap.put("updateName",trueName);
        this.companyEatApplyDAO.updCompanyEatApplyStatusById(companyEatApplyMap);
        

    }
    
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    
    public void updateEatApplyConnection(Integer id, String trueName) {
        //step1:请求参数
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("id", id);
        paramMap.put("isConnection", CompanyEatApplyModel.IS_CONNECTION_YES);
        paramMap.put("updatedName", trueName);
        this.companyEatApplyDAO.updateEatApplyConnection(paramMap);
    }

   

    

}
